<?php
namespace Framework;


/**
 * 
 * 注释中例子皆假设被请求的URL是 http://example.com/admin/index.php/product?id=100
 */
class Request
{
	public $_pathInfo;
	public $_scriptFile;

    public function method()
    {
        if (isset($_SERVER['REQUEST_METHOD'])) {
            return strtoupper($_SERVER['REQUEST_METHOD']);
        }

        return 'GET';
    }

    public function isMethod($method)
    {
        return $this->method() == strtoupper($method);
    }

    /**
     * 返回请求的路径信息
     * 返回 /product， 这个是入口脚本之后，问号之前（查询字符串）的部分
     */
    public function path()
    {
        // return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : null;
        if( isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO']!='' ){
        	$pathinfo = $_SERVER['PATH_INFO'];

        }else{
        	$pathinfo = strpos($_SERVER['REQUEST_URI'], '?') ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'];
        }

        return $pathinfo;
    }

    /**
     * 不含 Query String 的完整链接
     * @param query 布尔值 是否含query参数
     * http://example.com/admin/index.php
     */
    public function url($query=false)
    {
        $url = $this->host() .'/'. ltrim($this->path(), '/');

        if($query){
            $url .= '?' . $this->query();
        }

        return $url;
    }

    /**
     * 主机名
     * http://example.com
     */
    public function host()
    {
        return isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
    }

    /**
     * 端口
     * 80
     */
    public function port()
    {
        return isset($_SERVER['SERVER_PORT']) ? (int) $_SERVER['SERVER_PORT'] : null;
    }

    /**
     * 查询字符串
     * id=100
     */
    public function query()
    {
        return isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
    }

    public function is($patterns){
    	$path = trim($this->path(), '/');

    	if( !strstr($patterns, '*') ){ 
    		//完全匹配模式
    		return ($patterns==$path) ? true : false ;
    	}

    	//通配符模式
    	$patterns = str_replace('/', '\/', $patterns);
    	$rule = str_replace('*', '([A-Za-z0-9\-\_\/]+)', $patterns);
        $rule = '/^' . $rule . '$/';
 
        return is_scalar($path) && 1 === preg_match($rule, (string) $path);
    }
}